import { View, StyleSheet, Text, NativeModules, Platform } from 'react-native';
import BaseSidebar from 'components/BaseSidebar';
import { Marker, MapView, AMapSdk, Circle, Cluster } from 'react-native-amap3d';
import { SvgXml } from 'react-native-svg';
import fire from 'assets/Images/fire.svg';
import help from 'assets/Images/help.svg';
import xhs from 'assets/Images/xhs.svg';
import React, {
  createContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import { getPagePolice, getFireFacilityLocationData } from 'api/combat';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import useDimensions from 'hooks/useDimensions';
import { useAppSelector } from 'app/store';
import { MapCenter } from 'enums/Map'
type xfsListItem = Api.resBody['消防设施表'] & {
  location: GlobalMap.location;
};
type ListItem = Api.resBody['警情信息主表'] & {
  LatLng: GlobalMap.location;
};
type BaseSidebarRefType = {
  updateState: () => void;
  setInactive: (value: boolean) => void;
};
type inactive = 0 | 1 | 2;
export interface ContextType {
  changeMarker: (location: GlobalMap.location, index: inactive) => void;
  List: ListItem[];
  StartNav: (end: { target: GlobalMap.location }) => void;
  inactive: inactive;
  xfsList: xfsListItem[];
  location?: GlobalMap.location;
}
export const Context = createContext<ContextType | null>(null);
const NativeNavi = NativeModules.NativeNavi;
AMapSdk.init(
  Platform.select({
    android: '0025134cd057421227576464cec38820',
  }),
);
const Stack = createNativeStackNavigator();
export default () => {
  const hp = useDimensions();
  const token = useAppSelector(state => state.user.token);
  const [inactive, setInactive] = useState<inactive>(0);
  const MapRef = useRef<MapView | null>(null);
  const markers = useRef(new Map());
  const [List, setList] = useState<ListItem[]>([]);
  const [location, setLocation] = useState<GlobalMap.location>();
  const BaseSidebarRef = useRef<BaseSidebarRefType>();
  const ClusterRef = useRef<Cluster>();
  const onPress = (location: GlobalMap.location, index: inactive) => {
    MapRef.current?.moveCamera(
      {
        target: location,
        zoom: 15,
      },
      800,
    );
    BaseSidebarRef.current?.updateState();
    setInactive(index);
  };
  const onLocation = (event: {
    nativeEvent: {
      coords: GlobalMap.location;
    };
  }) => {
    if (!location) {
      const { latitude, longitude } = event.nativeEvent.coords;
      setLocation({ latitude, longitude });
    }
  };
  const StartNav = (end: { target: GlobalMap.location }) => {
    NativeNavi.startActivityFromJS('com.commander.BasicNaviActivity', {
      ...end.target,
      token,
    });
  };
  const [xfsList, setXfsList] = useState<xfsListItem[]>([]);
  useEffect(() => {
    getPagePolice().then(data => {
      const currentList = data?.map(item => {
        return {
          ...item,
          LatLng: {
            latitude: +(item.incidentLatitude as unknown as string),
            longitude: +(item.incidentLongitude as unknown as string),
          },
        };
      });
      setList(currentList);
    });
  }, []);
  useEffect(() => {
    if (List.length > 0) {
      const { latitude, longitude } = List[inactive].LatLng;
      getFireFacilityLocationData({
        centerLat: +latitude,
        centerLng: +longitude,
        radius: 950,
      }).then(data => {
        const List = (data ?? []).map(item => {
          const { lat: latitude = 0, lng: longitude = 0, ...rest } = item;
          return {
            location: {
              latitude,
              longitude,
            },
            ...rest,
          };
        });
        setXfsList(List);
      });
      onPress(
        {
          latitude: +latitude,
          longitude: +longitude,
        },
        inactive ?? 0,
      );
    }
  }, [List, inactive]);
  const currentXfsList = useMemo(() => {
    return xfsList.map((item, index) => {
      return {
        position: item.location,
        properties: { key: `Marker${index}`, name: item.ownerAddress, index },
      };
    });
  }, [xfsList]);
  return (
    <View style={style.container}>
      <MapView
        mapType={3}
        myLocationButtonEnabled
        myLocationEnabled
        buildingsEnabled
        compassEnabled={false}
        onLocation={onLocation}
        scaleControlsEnabled={false}
        ref={MapRef}
        onCameraIdle={({ nativeEvent }) => {
          ClusterRef.current?.update(nativeEvent);
        }}
        initialCameraPosition={{
          target: MapCenter,
          zoom: 15,
        }}
        trafficEnabled>
        {List.map((item, index) => (
          <Marker
            key={index}
            onPress={onPress.bind(null, item.LatLng, index as inactive)}
            position={item.LatLng}>
            <SvgXml
              {...{
                width: (inactive === index ? 60 : 32) * hp,
                height: (inactive === index ? 75 : 32) * hp,
              }}
              xml={item.incidentType === '火灾扑救' ? fire : help}
            />
            {inactive === index && (
              <Text
                style={{
                  fontSize: 20 * hp,
                  fontWeight: '700',
                  color: 'white',
                }}>
                救援点
              </Text>
            )}
          </Marker>
        ))}
        {List.length > 0 && (
          <Circle
            radius={1000}
            center={List.at(inactive)?.LatLng as ListItem['LatLng']}
            strokeWidth={0}
            fillColor="rgba(170,171,166,0.8)"></Circle>
        )}

        {
          // @ts-ignore  AMap3D 组件ts未定义好
          <Cluster
            points={currentXfsList}
            // @ts-ignore
            ref={ClusterRef}
            renderMarker={item => {
              return (
                <Marker
                  key={item.properties.key}
                  ref={ref => {
                    markers.current.set(item.properties.index, ref);
                  }}
                  onPress={() => {
                    markers.current.get(item.properties.index).showInfoWindow();
                  }}
                  // @ts-ignore
                  onStartNav={() => {
                    StartNav({ target: item.position });
                  }}
                  position={item.position}>
                  <View
                    style={{
                      alignItems: 'center',
                    }}>
                    <SvgXml
                      {...{
                        width: 32 * hp,
                        height: 32 * hp,
                      }}
                      xml={xhs}
                    />
                    {
                      <Text
                        style={{
                          fontSize: 14,
                          fontWeight: '700',
                          color: 'black',
                        }}>
                        {item.properties.name}
                      </Text>
                    }
                  </View>
                </Marker>
              );
            }}></Cluster>
        }
      </MapView>
      <Context.Provider
        value={{
          List,
          changeMarker: onPress,
          StartNav,
          inactive,
          xfsList,
          location,
        }}>
        <BaseSidebar
          ref={BaseSidebarRef}
          ExpandLabel="警情列表"
        >
          <Stack.Navigator
            initialRouteName="SidebarIndex"
            screenListeners={({ navigation }) => {
              return {
                state: () => {
                  // setInactive(navigation.canGoBack());
                  BaseSidebarRef.current?.setInactive(navigation.canGoBack());
                },
              };
            }}
            screenOptions={{
              headerShown: false,
              contentStyle: {
                backgroundColor: 'transparent',
              },
            }}>
            <Stack.Screen
              name="SidebarIndex"
              getComponent={() =>
                require('views/Home/components/SidebarIndex').default
              }
            />
            <Stack.Screen
              name="PoliceIntelligence"
              getComponent={() =>
                require('views/Home/components/PoliceIntelligence').default
              }
            />
            <Stack.Screen
              name="factory"
              getComponent={() =>
                require('views/Home/components/factory').default
              }
            />
          </Stack.Navigator>
        </BaseSidebar>
      </Context.Provider>
    </View>
  );
};
const style = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
    flexDirection: 'row',
  },
});
